package cn.gan.loveofsoul.controller;

import cn.gan.loveofsoul.commons.result.ConfigContents;
import cn.gan.loveofsoul.commons.result.ErrorMessage;
import cn.gan.loveofsoul.commons.result.Result;
import cn.gan.loveofsoul.commons.result.StatusCode;
import cn.gan.loveofsoul.commons.utils.RedisUtil;
import cn.gan.loveofsoul.entity.User;
import cn.gan.loveofsoul.entity.vo.UserVO;
import cn.gan.loveofsoul.exception.BusinessException;
import cn.gan.loveofsoul.service.IRelationshipService;
import cn.gan.loveofsoul.service.IUserService;
import cn.hutool.core.map.MapUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;


import java.util.HashMap;
import java.util.Objects;
import java.util.Optional;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author ganwh
 * @since 2023-10-26
 */
@Controller
@RequestMapping("/relationship")
public class RelationshipController {

    @Autowired
    private IUserService userService;

    @Autowired
    private IRelationshipService relationshipService;

    @Autowired
    private RedisUtil redisUtil;

    /**
     * 功能描述: 发起绑定（两小时有效期：7200秒）
     *
     * @param userId
     * @return cn.gan.loveofsoul.commons.result.Result
     * @author ganwh 2023/10/31 11:57
     */
    @GetMapping("/initiatingBinding")
    @ResponseBody
    public Result initiatingBinding(Integer userId) {
        Optional<User> optional = userService.getOptById(userId);
        optional.orElseThrow(() -> new BusinessException(StatusCode.NOT_FOUND, ErrorMessage.USER_NOT_EXIST));
        User user = optional.get();
        UserVO userVO = User.convert2UserVO(user);
        String key = DigestUtil.md5Hex(String.valueOf(userId));
        Object obj = redisUtil.get(ConfigContents.INITIATING_BINDING_REDIS_KEY_PREFIX + key);
        boolean b;
        if (Objects.isNull(obj)) {
            b = redisUtil.set(ConfigContents.INITIATING_BINDING_REDIS_KEY_PREFIX + key, userVO, 7200L);
        } else {
            b = redisUtil.expire(ConfigContents.INITIATING_BINDING_REDIS_KEY_PREFIX + key, 7200L);
        }
        if (b) {
            HashMap<String, Object> resMap = MapUtil.newHashMap();
            resMap.put("userName", userVO.getUserName());
            resMap.put("token", key);
            return new Result(StatusCode.SUCCESS, ErrorMessage.SUCCESS, resMap);
        }
        return new Result(StatusCode.ERROR, ErrorMessage.SYSTEM_ERROR);
    }

    /**
     * 功能描述: 获取邀请绑定的用户信息
     *
     * @param token
     * @return cn.gan.loveofsoul.commons.result.Result
     * @author ganwh 2023/10/31 15:20
     */
    @GetMapping("/getBindingUser")
    @ResponseBody
    public Result getBindingUser(String token) {
        Object obj = redisUtil.get(ConfigContents.INITIATING_BINDING_REDIS_KEY_PREFIX + token);
        if (Objects.isNull(obj)) {
            return new Result(StatusCode.UNAUTHORIZED, ErrorMessage.INVITATION_HAS_EXPIRED);
        }
        UserVO userVO = JSONObject.parseObject(JSONObject.toJSONString(obj), UserVO.class);
        Optional<User> optional = userService.getOptById(userVO.getUserId());
        optional.orElseThrow(() -> new BusinessException(StatusCode.NOT_FOUND, ErrorMessage.INVITATION_USER_NOT_EXIST));
        return new Result(StatusCode.SUCCESS, ErrorMessage.SUCCESS, userVO);
    }

    /**
     * 功能描述: 接受绑定
     *
     * @param targetUserId
     * @param sourceUserId
     * @return cn.gan.loveofsoul.commons.result.Result
     * @author ganwh 2023/10/31 15:20
     */
    @GetMapping("/binding")
    @ResponseBody
    public Result binding(@RequestParam("targetUserId") Integer targetUserId,
                          @RequestParam("currentUserId") Integer currentUserId) {
        if (Objects.isNull(targetUserId)) {
            throw new BusinessException(StatusCode.BAD_REQUEST, ErrorMessage.MISSING_PARAMETER);
        }
        if (Objects.isNull(currentUserId)) {
            throw new BusinessException(StatusCode.BAD_REQUEST, ErrorMessage.MISSING_PARAMETER);
        }
        return relationshipService.binding(targetUserId, currentUserId);
    }

    /**
     * 功能描述: 获取当前用户情侣用户信息
     *
     * @param userId
     * @return cn.gan.loveofsoul.commons.result.Result
     * @author ganwh 2023/11/1 10:56
     */
    @GetMapping("/queryRelationship")
    @ResponseBody
    public Result queryRelationship(Integer userId) {
        if (Objects.isNull(userId)) {
            throw new BusinessException(StatusCode.BAD_REQUEST, ErrorMessage.MISSING_PARAMETER);
        }
        return relationshipService.queryRelationship(userId);
    }
}
